package com.itheima.itheima.controller;

import com.itheima.util.FileUtils;
import com.itheima.util.RedisConstant;
import com.itheima.util.RedisUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Set;

@RestController
@RequestMapping("setmeal")
public class UploadController {

    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    /**
     *文件上传必须使用psot类型
     * */
    @PostMapping("/upload")
    public String upload(@RequestParam("myfile") MultipartFile multipartFile) throws IOException {
        //multipartFile.getOriginalFilename() 上传的文件名
        //multipartFile.getInputStream() 上传的文件流
        String path = FileUtils.upload(multipartFile.getOriginalFilename(),multipartFile.getInputStream());
        //将path存放到file:allset
//        redisTemplate.opsForSet().add("file:allset",path);
        RedisUtil.addToSet(RedisConstant.ALL_SETMEAL_PIC_SET,path);
        //对file:{path}设置有效时间
//        redisTemplate.opsForValue().set("file:" + path,1,300L, TimeUnit.SECONDS);
        //优化后的：
        RedisUtil.set(RedisConstant.SINGLE_PIC+path,1,1L);
        return path;
    }



    //这里是存储了两份，一份是临时的，24小时后过期，一份是持久的，当临时节点没了证明已经过期，然后去
    //阿里云删除，之后再在该持久处将其删除，避免下一次删除重复（虽然不会删除，但浪费时间）
    //当我们得到真正要存储的数据从持久节点移除，这就不会误删了

    @RequestMapping("/clear")
    public void clearImg(){
        //用set存储数据
        //取出所有元素：（file:allset
//        Set<Object> allset = redisTemplate.opsForSet().members("file:allset");
        Set<Object> allset =RedisUtil.getMembersOfSet(RedisConstant.ALL_SETMEAL_PIC_SET);
        if (allset!=null){
            for (Object path: allset) {
                String filekey="file:"+path;
                if (redisTemplate.hasKey(filekey)==false){
                    //如果发现没有改数据，证明过期，删除
                    FileUtils.deletefile((String)path);
                    //从临时节点移出去
//                    redisTemplate.opsForSet().remove("file:allset",path);
                    RedisUtil.removeSetMember(RedisConstant.ALL_SETMEAL_PIC_SET,path);
                }
            }
        }
    }
}
